<template>
  <div class="index-container">
    <div class="index-title">
      <!-- <div class="responsible-person">
        <span>责任人：</span><span>{{ props.quota }}</span>
      </div> -->
      <div class="responsible-company">
        <span>责任单位：</span><span>{{ props.quota.department }}</span>
      </div>
      <div @click="favBtn">
        <img v-if="star == 1" class="fav-btn" src="../../assets/favBtn.png" />
      </div>
      <div @click="favBtn">
        <img v-if="star == 0" class="fav-btn" src="../../assets/xingxing.png" />
      </div>
    </div>
    <div>
      <div v-if="props.detail.mapOutPutEntity.cgjybzIndustryDataHotmap?.length" class="area-title">
        区市分布
      </div>
      <div class="anomaly-echarts">
        <div
          v-if="props.detail.mapOutPutEntity.cgjybzIndustryDataHotmap?.length"
          class="echartClass"
        >
          <div
            v-for="item in !isExpand ? copyAnomalyTotal : mapEcharts"
            :key="item"
            class="echarts-box"
          >
            <div class="echarts-title">{{ item.name }}</div>
            <div class="echarts-lint">
              <div class="echarts-left">
                <div class="echarts-pad" :style="{ width: item.rata }" />
              </div>
              <div class="echarts-num">
                <div>{{ item.value }}</div>
                <div class="numlin" />
                <div>{{ item.rata }}</div>
              </div>
            </div>
          </div>
        </div>
        <div v-if="mapEcharts && mapEcharts.length > 6" class="more">
          <div class="more-name" @click="moreClick">{{ !isExpand ? '更多' : '收起' }}</div>
          <SvgIcon style="font-size: 14px" :icon-class="'more'" />
        </div>
      </div>

      <div
        v-if="props.detail.pieOutPutEntity?.lineBarVo?.series?.length"
        class="trend-change"
      >
        <div  class="trend-title">
          趋势变化
        </div>
        <div  class="trend-echarts-unit">
          {{props.detail.pieOutPutEntity.lineBarVo.type}}/{{props.detail.pieOutPutEntity.lineBarVo.unit}}
        </div>
        <div :id="`trend-echarts${props.quota.id}`" style="width: 290px; height: 150.99px" />
      </div>
      <div
        v-if="hasData"
        class="trend-change"
      >
        <div
          class="trend-title"
        >
          结构分析
        </div>
        <!-- <img v-else src="../../assets/no_data.png" class="noData2" /> -->
        <div
          :id="`structure-echarts${props.quota.id}`"
          class="chart-pie"
          :style="{ height: pieChartHeight + 'vw' }"
        />
      </div>
      <!-- {{ detail }}<br /> -->
      <!-- {{ quota }} -->
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { computed, ref, reactive, toRefs, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { useQuotaStore } from '@/store'

import FavServe from '@/api/fav'

const quotaStore = useQuotaStore()
const props = defineProps({
  quota: {
    type: Object,
    default: null
  },
  detail: {
    type: Object,
    default: null
  }
})
// 根据图例数量计算饼图高度
const pieChartHeight = ref(100 / document.documentElement.clientWidth * 151)
watch(
  () => pieChartHeight.value,
  () => {
    nextTick(() => {
      structureEcharts?.resize()
    })
  }
)
// 判断是否有数据
const hasData = computed(() => props.detail?.pieOutPutEntity?.echartPieEntity?.series[0]?.data?.length)
const isExpand = ref(false)
const moreClick = () => {
  isExpand.value = !isExpand.value
}
const getMap = ref([])
const star = ref(props.quota.collectFlag)
const mapEcharts = ref([])
const lineEcharts = ref([])
const lineEchartsServe = ref([])
const pieEcharts = ref([])
// 拷贝前五个
let copyAnomalyTotal = reactive([])
let trendEcharts, structureEcharts

const moreBtn = ref(false)
const btnShow = ref(true)

// const emit = defineEmits(['Favrefresh'])
const favBtn = async () => {
  if (star.value == 0) {
    star.value = 1
  } else {
    star.value = 0
  }
  try {
    await FavServe.selCollectById({
      collect: props.quota?.id,
      flag: props.quota.collectFlag || 0
    }).then(() => {
      // emit('Favrefresh')
      quotaStore.fetchFavQuotaList()
    })
  } catch (error) {
    console.log(error)
  }
}
onMounted(() => {
  // 获取区域数据
  const current = (props.detail?.mapOutPutEntity?.cgjybzIndustryDataHotmap || []).sort(function (
    a,
    b
  ) {
    return b.value - a.value
  })
  getMap.value = (current || []).map(item => {
    //  const sum += item.value
    let sum = 0
    for (let i = 0; i < current.length; i++) {
      sum += Number(current[i].value)
    }
    console.log('mapEcharts.value', sum)
    const single = {
      name: item.district,
      value: item.value,
      rata: `${((item.value * 100) / sum).toFixed(2)}% `
    }
    return mapEcharts.value.push(single)
  })
  if (mapEcharts.value.length >= 5) {
    copyAnomalyTotal = mapEcharts.value.slice(0, 5)
  } else {
    copyAnomalyTotal = mapEcharts.value
  }
  // 获取折线图数据
  lineEcharts.value = props.detail?.pieOutPutEntity?.lineBarVo?.xaxis
  lineEchartsServe.value = props.detail?.pieOutPutEntity?.lineBarVo?.series
  // 获取饼图数据
  pieEcharts.value = props.detail?.pieOutPutEntity?.echartPieEntity?.series[0]?.data?.length
    ? props.detail.pieOutPutEntity.echartPieEntity.series[0].data
    : []
  pieEcharts.value.sort(function(a,b){
    return b.value - a.value
  })
  // const pieLegendL = pieEcharts.value.slice(0, 3)
  const pieLegendR = pieEcharts.value // .slice(3, 6)
  // console.log('pieEcharts.value',pieEcharts.value);
  // 折线图
  if (props.detail.pieOutPutEntity?.lineBarVo?.series?.length) {
    trendEcharts = echarts.init(document.getElementById(`trend-echarts${props.quota.id}`))

    trendEcharts.setOption({
      grid: {
        containLabel: true,
        top: 40,
        left: 10,
        right: 5,
        bottom: 10
      },
      tooltip: {
        backgroundColor: 'rgba(9, 20, 37, 0.75)',
        borderColor: '#48607f',
        borderWidth: 1,
        confine: true,
        textStyle: {
          fontSize: 8,
          color: '#fff',
          fontFamily: 'PingFang-SC-Medium'
        },
        formatter: '{b} : {c}'
        // padding: [10, 25],
        // axisPointer: {
        //   type: 'none'
        // }
      },
      xAxis: [
        {
          show: true,
          type: 'category',
          // inverse: true,
          data: lineEcharts.value,

          // max: 10,
          axisLine: {
            show: true
          },
          axisTick: {
            show: true
          },
          axisLabel: {
            show: true,
            rotate: 45,
            textStyle: {
              fontSize: '8'
            }
          },
          splitLine: { show: true }
        }
      ],
      yAxis: {
        type: 'value',
        show: true,
        axisLine: {
          show: true
        },
        axisTick: {
          show: true
        },
        axisLabel: {
          show: true
        }
      },
      series: [
        {
          name: 'Email',
          type: 'line',
          stack: 'Total',
          // areaStyle: {},

          emphasis: {
            focus: 'series'
          },
          label: {
            show: true,
            formatter: '{c}',
            textStyle: {
              color: '#ffffff',
              fontSize: 10,
              backgroundColor: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                { offset: 0, color: '#11def5 ' },
                { offset: 1, color: '#4389f3 ' }
              ]),
              //  lineHeight: "20",
              borderRadius: 15,
              padding: 2
            },
            position: 'center',
            align: 'center',
            offset: [0, -20]
          },
          barWidth: 11.54,

          itemStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#11def5 ' },
                { offset: 1, color: '#4389f3 ' }
              ]), // 改变折线点的颜色
              lineStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                  { offset: 0, color: '#11def5 ' },
                  { offset: 1, color: '#4389f3 ' }
                ])
              }
            }
            //   normal: {
            //     barBorderRadius: 2.56,

            //   }
          },
          data: lineEchartsServe.value
          // barGap: 50
        }
      ]
    })
  }

  // 饼图
  if (hasData) {
    const width = document.documentElement.clientWidth
    const height = Math.max(151, pieEcharts.value.length * 29)
    // 文字超过14字时会换行，换行会增加高度，所以最终高度要加上换行高度
    const wrapHeight = pieEcharts.value.filter(item => item.name.length > 14).length * 8
    pieChartHeight.value = 100 / width * (height + wrapHeight)
    structureEcharts = echarts.init(document.getElementById(`structure-echarts${props.quota.id}`))
    const colorList = [
      {
        gradientStart: '#3377ff', //   渐变
        gradientEnd: '#4da5ff' //
      },
      {
        gradientStart: '#00a7b3', //   渐变
        gradientEnd: '#55f2f2' //
      },
      {
        gradientStart: '#33aaff', //   渐变
        gradientEnd: '#33ccff' //
      },
      {
        gradientStart: '#f2bc19', //   渐变
        gradientEnd: '#ffdd33' //
      },
      {
        gradientStart: '#f26500', //   渐变
        gradientEnd: '#ffa64d' //
      },
      {
        gradientStart: '#6e26ff', //   渐变
        gradientEnd: '#9580ff' //
      },
      {
        gradientStart: '#8e26ff', //   渐变
        gradientEnd: '#aa80ff' //
      },
      {
        gradientStart: '#ae26ff', //   渐变
        gradientEnd: '#af2688' //
      },
      {
        gradientStart: '#a9eb30', //   渐变
        gradientEnd: '#a9eb30' //
      },
      {
        gradientStart: '#ba03c0', //   渐变
        gradientEnd: '#ba03c0' //
      },
      {
        gradientStart: '#36bcf1', //   渐变
        gradientEnd: '#36bcf1' //
      },
      {
        gradientStart: '#f1bf36', //   渐变
        gradientEnd: '#f1bf36' //
      },
      {
        gradientStart: '#a13ca5', //   渐变
        gradientEnd: '#a13ca5' //
      },
      {
        gradientStart: '#30ebb3', //   渐变
        gradientEnd: '#30ebb3' //
      },
      {
        gradientStart: '#558073', //   渐变
        gradientEnd: '#558073' //
      },

      {
        gradientStart: '#a5893c', //   渐变
        gradientEnd: '#a5893c' //
      }
    ]

    structureEcharts.setOption({
      tooltip: {
        backgroundColor: 'rgba(9, 20, 37, 0.75)',
        borderColor: '#48607f',
        borderWidth: 1,
        confine: true,
        textStyle: {
          fontSize: 8,
          color: '#fff',
          fontFamily: 'PingFang-SC-Medium'
        },
        formatter: '{b} : {c}%'
        // padding: [10, 25],
        // axisPointer: {
        //   type: 'none'
        // }
      },
      grid: {
        top: '0%',
        left: '0%',
        right: '0%',
        bottom: '0%'
      },
      legend: [
        // {
        //   data: pieLegendL,
        //   x: 'left',
        //   trigger: 'item',
        //   top: '25%',
        //   left: '5%',
        //   itemWidth: 8, // 设置icon宽度
        //   itemHeight: 8, // 设置icon高度
        //   icon: 'circle',
        //   itemGap: 8,
        //   orient: 'vertical',
        //   formatter: function (name) {
        //     let res = {}
        //     for (let i = 0; i < pieEcharts.value.length; i++) {
        //       if (name == pieEcharts.value[i].name) {
        //         res = {
        //           name: pieEcharts.value[i].name,
        //           value: pieEcharts.value[i].value,
        //           rate: pieEcharts.value[i].rate,
        //           unit: pieEcharts.value[i].unit
        //         }
        //       }
        //     }
        //     return `${res.name} \n ${res.rate}|${res.value}${res.unit}`
        //   },
        //   textStyle: {
        //     fontSize: 9
        //   },
        //   rich: {
        //     // 图例各项的间隔以及图例颜色大小

        //     a: {
        //       color: 'red',
        //       lineHeight: 10
        //     },
        //     b: {
        //       color: '#fff',
        //       lineHeight: 10
        //     }
        //   }
        // },
        {
          data: pieLegendR,
          x: 'right',
          trigger: 'item',
          // top: '25%',
          left: '45%',
          itemWidth: 8, // 设置icon宽度
          itemHeight: 8, // 设置icon高度
          icon: 'circle',
          itemGap: 8,
          orient: 'vertical',
          textStyle: {
            fontSize: 9
          },
          formatter: function (name) {
            const record = pieEcharts.value.find(item => item.name === name)
            const showName = record.name.length > 14 ? `${record.name.substring(0, 14)}\n${record.name.substring(14)}` : record.name
            return `${showName}\n${record.rate}|${record.value}${record.unit}`
          },

          rich: {
            // 图例各项的间隔以及图例颜色大小

            a: {
              color: 'red',
              lineHeight: 10
            },
            b: {
              color: '#fff',
              lineHeight: 10
            }
          }
        }
      ],
      series: [
        {
          // hoverAnimation: true,
          // name: data.title,
          type: 'pie',
          minAngle: 4,
          radius: [35, 55],
          center: [70, '50%'],
          label: {
            normal: {
              show: false
            }
          },
          data: pieEcharts.value,
          itemStyle: {
            normal: {
              color: list => {
                return new echarts.graphic.LinearGradient(1, 0, 0, 0, [
                  {
                    // 左、下、右、上
                    offset: 0,
                    color: colorList[list.dataIndex]['gradientStart']
                  },
                  {
                    offset: 1,
                    color: colorList[list.dataIndex]['gradientEnd']
                  }
                ])
              }
            }
          }
        }
      ]
    })
  }

  //   window.onresize = function () {
  //     // 自适应大小
  //     myChart.resize()
  //   }
})

onUnmounted(() => {
  if (trendEcharts) {
    trendEcharts.dispose()
    trendEcharts = null
  }
  if (structureEcharts) {
    structureEcharts.dispose()
    structureEcharts = null
  }
})
</script>
<style scoped lang="less">
.index-container {
  background-color: #ffffff;
  .index-title {
    padding-left: 10px;
    margin-bottom: 14px;
    position: relative;
    .fav-btn {
      position: absolute;
      top: 15px;
      right: 20px;
      width: 19.23px;
      height: 19.23px;
    }
  }
}
.responsible-person {
  // width: 80.77px;
  height: 16.03px;
  padding-top: 15px;
  font-family: 'PingFang SC';
  font-weight: 500;
  color: #000000;
  font-size: 11.54px;
}
.responsible-company {
  /* width:138.46px; */
  height: 16.03px;
  font-family: 'PingFang SC';
  font-weight: 500;
  color: #000000;
  font-size: 11.54px;
  margin-top: 10px;
  padding-top: 10px;
}
.area-part {
  width: 290.46px;
  height: 300.81px;
  background: #f5f5f5;
  border-radius: 7.69px;
  margin-left: 10px;
  position: relative;
  // z-index: 1;
 
  .noData {
    position: absolute;
    top: 120px;
    left: 90px;
  }
}
.trend-change {
  width: 290.46px;
  // height: 181.99px;
  background: #f5f5f5;
  border-radius: 7.69px;
  margin-left: 10px;
  margin-top: 10.69px;
  // z-index: 9;
  position: relative;
  .trend-echarts-unit {
    position: absolute;
    // width: 56.15px;
    height: 14.42px;
    font-family: 'PingFang SC';
    font-weight: 600;
    color: #666666;
    font-size: 10.26px;
    top: 34px;
    left: 15px;
  }
  .trend-title {
    width: 61.54px;
    height: 21.47px;
    font-family: 'PingFang SC';
    color: #333333;
    font-size: 15.38px;
    padding: 11.54px 11.54px 0px 11.54px;
  }
  .noData2 {
    position: absolute;
    top: 50px;
    left: 90px;
  }
  .chart-pie {
    width: 100%;
    height: 150.99px;
  }
}
.more-btn {
  width: 290.46px;
  height: 34px;
  background: #f5f5f5;
  // z-index: 9;
  position: absolute;
  top: 240px;
  display: flex;

  justify-content: center;

  line-height: 40px;
  border-end-start-radius: 7.69px;
  .more-txt {
    width: 30.88px;
    height: 18.91px;
    font-family: 'PingFang SC';
    font-weight: 500;
    color: #4389f3;
    font-size: 13.46px;
    // letter-spacing: 19.23px;
    line-height: 40.31px;
  }
  .more-png {
    width: 13.46px;
    height: 13.46px;
    margin-top: 12px;
  }
}
.anomaly-echarts {
  width: 280px;
  // height: 311px;
  // background: #f5f5f5;
  border-radius: 8px;
  padding-bottom: 16px;

  .echarts-title {
    text-align: left;
    padding: 10px 8px 6px 8px;
    color: #333333;
    font-size: 13px;
    letter-spacing: 1px;
    line-height: 17px;
  }

  .echartClass {
    width: 310px;
    // height: 224px;
    // background: #ffffff;
    border-radius: 8px 8px 0 0;
    margin: auto;
    overflow: hidden;
    padding-bottom: 15px;

    .echarts-box {
      display: flex;
      flex-direction: column;
      height: 43px;

      .echarts-lint {
        display: flex;
        justify-content: space-between;

        .echarts-left {
          width: 216px;
          margin-left: 14px;
          height: 12px;

          .echarts-pad {
            height: 100%;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
            border-bottom-left-radius: 4px;
            border-bottom-right-radius: 4px;
            // width: 66%;
            background: linear-gradient(90deg, #9ea7fc 0%, #f3acfb 100%);
          }
        }

        .echarts-num {
          display: flex;
          align-items: center;
          margin-right: 15px;

          .numlin {
            width: 1px;
            transform: scaleX(0.5);
            height: 8px;
            background: #000;
            margin: 0 5px;
          }
        }
      }
    }

    .echartsNull {
      width: 100px;
      height: 92px;
      background: url(@/assets/no_data.png) no-repeat;
      background-size: cover;
    }
  }

  .echartsListNull {
    width: 329px;
    height: 224px;
    display: flex;
    align-items: center;
    justify-content: center;

    img {
      width: 100px;
      height: 92px;
    }
  }

  .more {
    width: 313px;
    height: 33px;
    border-top: 1px solid #e2e2e2;
    background: #ffffff;
    // margin: auto;
    border-radius: 0 0 8px 8px;
    display: flex;
    align-items: center;
    justify-content: center;

    .more-name {
      font-weight: 500;
      color: #888888;
      font-size: 13px;
    }

    .more-img {
      width: 14px;
      height: 14px;
      background: url(@/assets/anomalyIndex/bottom.png) no-repeat;
      background-size: 100% 100%;
      margin-left: 5px;
    }
  }
}
 .area-title {
    width: 61.54px;
    height: 21.47px;
    font-family: 'PingFang SC';
    color: #333333;
    font-size: 15.38px;
    padding-left: 8px;
  }
</style>
